package com.project.weather.component;

import com.project.weather.common.Constant;
import com.project.weather.pojo.UserBean;
import com.project.weather.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 拦截器，用于拦截前台的登录
 * 要在spring-mvc中配置拦截器<mvc:interceptor>
 * return false表示拦截，不向下执行
 * return true表示放行
 */
public class LogcostInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LogcostInterceptor.class);

    //首先会执行的方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) {

        String id = request.getSession().getId();
        log.info("==================== 请求的SessionId:{} ====================",id);

        //获取请求资源
        String requestURI = request.getRequestURI();
        log.info("requestURI========="+requestURI);

        //都不拦截的
        if(requestURI.contains("/weather/") || requestURI.contains("/account/") || requestURI.contains("/base/")) {
            log.info("请求url是以特定的开头,不拦截。uri={}",requestURI);
            return true;
        }

        //从session中获取对象
        UserBean userBean = (UserBean) ServletUtils.getSession().getAttribute(Constant.CURRENT_ACCOUNT);
//        UserBean userBean = (UserBean) request.getSession().getAttribute(Constant.CURRENT_ACCOUNT);
        log.info("获取用户对象==========={}",userBean);
        if(userBean==null||"user".equals(userBean.getRole_name())){

            response.setStatus(401);

            return false;
        }


        return true;
    }


    //返回ModelAndView之前执行的方法，面向切面编程中的体现，已经进入了controller
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {


    }


    //执行Handle完成之后执行的方法
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }
}